//
//  AVPlayerManager.swift
//  AVPlayerDemo
//
//  Created by dn56-macbook on 5/29/25.
//

import UIKit
import AVFoundation
import CommonCrypto

class AVPlayerManager {
    private var player: AVPlayer?
    private var cacheURL: URL!
    private var outputStream: OutputStream?
    private var inputStream: InputStream?

    func haveFile(_ url: URL)->Bool{
        let fileName = url.absoluteString.md5String + ".mp4"
        let path1 = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
        if FileManager.default.fileExists(atPath: path1.path){
            return true
        }
        return false
    }
    func startPlayback(url: URL) ->AVPlayer{
        // 创建缓存文件路径
        //cacheURL = self.getCacheUrl(url)
        let fileName = url.absoluteString.md5String + ".mp4"
        cacheURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
           
        // 初始化输出流（用于写入缓存）
        outputStream = OutputStream(toFileAtPath: cacheURL.path, append: true)
        outputStream?.open()
        
        // 初始化输入流（用于读取缓存）
        inputStream = InputStream(url: cacheURL)!
        inputStream?.open()
        
        // 创建 AVPlayer 并绑定播放源
        let asset = AVURLAsset(url: url)
        
        // 自定义资源加载器
        let resourceLoaderDelegate = ResourceLoaderDelegate(outputStream: outputStream, inputStream: inputStream)
        asset.resourceLoader.setDelegate(resourceLoaderDelegate, queue: resourceLoaderDelegate.resourceLoaderQueue)
        let playerItem = AVPlayerItem(asset: asset)
        player = AVPlayer(playerItem: playerItem)
        // 开始播放
        player?.play()
        
        // 启动下载任务
        //startDownloadTask(url: url)
        return player!
    }
    
    private func startDownloadTask(url: URL) {
//        if haveFile(url){
//            return
//        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        // 设置 Range 请求头（断点续传）
        if let fileData = try? Data(contentsOf: cacheURL), fileData.count > 0 {
            let range = "bytes=\(fileData.count)-"
            request.setValue(range, forHTTPHeaderField: "Range")
        }
        let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
            guard let self = self else { return }
            if let data = data {
                // 将下载的数据写入缓存文件
                self.writeDataToFile(data: data)
            }
        }
        task.resume()
    }
    
    private func writeDataToFile(data: Data) {
        debugPrint("======",data.count,Thread.isMainThread)
        if let outputStream = outputStream {
            let buffer = [UInt8](data)
            outputStream.write(buffer, maxLength: buffer.count)
            
           // outputStream.flush()
        }
    }
}
class ResourceLoaderDelegate: NSObject {
    private var outputStream: OutputStream?
    private var inputStream: InputStream?
    private var cachedData: Data = Data()
    public lazy var resourceLoaderQueue = DispatchQueue(label: "LZ_resourceLoaderQueue")
    init(outputStream: OutputStream?, inputStream: InputStream?) {
        super.init()
        self.outputStream = outputStream
        self.inputStream = inputStream
    }
}
extension ResourceLoaderDelegate: AVAssetResourceLoaderDelegate{
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
        
        DispatchQueue.global().async {
            debugPrint("===================")
            var buffer = [UInt8](repeating: 0, count: 1024)
            while self.inputStream?.hasBytesAvailable == true {
                let bytesRead = self.inputStream?.read(&buffer, maxLength: buffer.count) ?? 0
                if bytesRead > 0 {
                    let data = Data(bytes: buffer, count: bytesRead)
                    debugPrint("===================",buffer)
                    loadingRequest.dataRequest?.respond(with: data)
                }
            }
        }
        return true
        
    }
    
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
        loadingRequest.finishLoading()
       
    }
}
extension String{
    //字符串MD5加密
    var md5String: String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)

        let hash = NSMutableString()

        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deallocate()
        return hash as String
    }
}
